import { ref, Ref } from "vue"

type collapseStateType = {
  [key: number]: boolean
}

const collapseState: collapseStateType = {
  0: false,
  1: true,
  2: true,
}

let stateIndex = Number(sessionStorage.getItem("collapse")) || 0
// 是否沉浸式
const setImmersive = (value: number) => value === 2
// 定时器
let timer: number | null = null
// ref
const immersive_menu = ref<boolean>(false)
const immersive = ref(setImmersive(Number(stateIndex)))
const collapse = ref<boolean>(collapseState[stateIndex])
// useCollaps
export function useCollaps() {
  const useGetCollasp = () => collapse.value
  const useSetCollaps = (num?: number) => {
    if (num) {
      stateIndex = num
    } else {
      stateIndex++
    }
    console.log("num", num)
    if (stateIndex > 2) {
      stateIndex = 0
      useImmersiveMenu(false)
    }
    // 沉浸式
    immersive.value = setImmersive(stateIndex)
    // collapse
    collapse.value = collapseState[stateIndex]
    // sessionStorage
    sessionStorage.setItem("collapse", JSON.stringify(stateIndex))
  }
  const useCollapsLeave = () => {
    // 如果存在定时器，先清除
    if (timer) {
      useClearTimer()
    }
    // 开启定时器
    timer = setTimeout(() => {
      useCloseImmersiveMenu()
      useClearTimer()
    }, 500)
  }

  /** 清除定时器 */
  const useClearTimer = () => {
    clearTimeout(timer as any)
    timer = null
  }

  /** 更新沉浸式菜单 */
  const useImmersiveMenu = (value: boolean) => (immersive_menu.value = value)

  /** 展开沉浸式菜单 */
  const useOpenImmersiveMenu = () => {
    if (stateIndex !== 2) {
      return
    }
    useImmersiveMenu(true)
  }

  /** 关闭沉浸式菜单 */
  const useCloseImmersiveMenu = () => useImmersiveMenu(false)

  /** 是否显示沉浸式菜单 */
  const useIsOpenImmersiveMenu = () => immersive_menu.value

  /** 是否沉浸式 */
  const useIsImmersive = () => immersive.value

  return {
    useGetCollasp,
    useSetCollaps,
    useCollapsLeave,
    useOpenImmersiveMenu,
    useCloseImmersiveMenu,
    useClearTimer,
    useIsOpenImmersiveMenu,
    useIsImmersive,
  }
}
